package inet.app.vod.activity.film;

import inet.app.vod.activity.R;
import inet.app.vod.activity.account.LoginActivity;
import inet.app.vod.activity.account.RegisterActivity;
import inet.app.vod.activity.common.BaseActivity;
import inet.app.vod.adapter.FilmSuggestAdapter;
import inet.app.vod.config.AppConstants;
import inet.app.vod.db.DaoFactory;
import inet.app.vod.db.DaoVideo;
import inet.app.vod.facebook.CommentView;
import inet.app.vod.net.http.VolleyClient;
import inet.app.vod.net.http.VolleyListener;
import inet.app.vod.object.MovieModel;
import inet.app.vod.object.ResultJsonModel;
import inet.app.vod.parser.Parse;
import inet.app.vod.util.MyUtil;
import inet.app.vod.view.MySpinner;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.android.volley.VolleyError;
import com.inet.app.framework.bitmap.UniversalImageUtil;
import com.inet.app.framework.intentutil.LaunchIntent;
import com.inet.app.framework.util.Log;
import com.inet.app.framework.widget.MyToast;

public class IPhimDetailActivity extends BaseActivity implements
		View.OnClickListener {

	private final static String TEXT_COLOR = "white";
	public final static String BACKGROUND_COLOR = "black";
	private final static int TEXT_SIZE = 3;

	private MySpinner mEpisodeSpinner;
	private Button mDetailTab;
	private Button mCommentTab;
	private Button mSuggestTab;
	private ViewFlipper mViewFlipper;
	private ListView mSuggestList;
	private CommentView mCommentView;
	private Resources mResources;
	private AlertDialog mLoginDlg;
	private TextView mEpisode;

	private MovieModel mMovie;
	private String mHomeId;
	private List<MovieModel> mSuggestMovie = new ArrayList<MovieModel>();
	private FilmSuggestAdapter mSuggestMovieAdapter;
	private DaoVideo mDaoFilm;
	private String[] episodes;
	private int epCurrent = 1;

	/**
	 * Load other movie from suggest list view
	 */
	AdapterView.OnItemClickListener suggestListListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			MovieModel movie = mSuggestMovie.get(position);
			Bundle bundle = new Bundle();
			bundle.putSerializable("movie", movie);
			bundle.putString("home_id", mHomeId);
			LaunchIntent.start(IPhimDetailActivity.this,
					IPhimDetailActivity.class, bundle);
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.detail_button:
			/* show phim chi tiet */
			resetTab(0);
			break;
		case R.id.comment_button:
			/* show binh luan */
			resetTab(1);
			showComments();
			break;
		case R.id.suggest_button:
			/* show list phim goi y */
			resetTab(2);
			if (mSuggestMovie == null || mSuggestMovie.size() == 0) {
				// request suggest movie
				requestSuggestMovies();
			}
			break;
		case R.id.play_layout:
			if (!isLogin()) {
				mLoginDlg = new AlertDialog.Builder(this).create();
				mLoginDlg.setTitle("Tài khoản");
				mLoginDlg.setMessage("Bạn hãy đăng nhập để xem bộ phim này");
				mLoginDlg.setButton(AlertDialog.BUTTON_POSITIVE,
						getString(R.string.dang_nhap),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int id) {
								LaunchIntent.start(IPhimDetailActivity.this,
										LoginActivity.class);
							}
						});
				mLoginDlg.setButton(AlertDialog.BUTTON_NEGATIVE, "Đóng",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								mLoginDlg.dismiss();
							}
						});
				mLoginDlg.setButton(AlertDialog.BUTTON_NEUTRAL,
						getString(R.string.dang_ki),
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								LaunchIntent.start(IPhimDetailActivity.this,
										RegisterActivity.class);
							}
						});
				mLoginDlg.show();

			} else {
				Bundle bundle = new Bundle();
				bundle.putSerializable("movie", mMovie);
				bundle.putString("home_id", mHomeId);
				bundle.putInt("episode", epCurrent);
				LaunchIntent.start(this, VideoPlayerActivity.class, bundle);
			}
		}

	}

	private void showComments() {
		if (!mCommentView.isStarted()) {
			MyToast.show(this, getString(R.string.loi_comment_facebook));
			mCommentView.loadComments(mMovie.getFbLink());
		}
	}

	private void requestSuggestMovies() {
		VolleyClient.requestSuggests(mHomeId, mMovie.getId(),
				new VolleyListener(this) {

					@Override
					public void onSuccess(String response) {
						Log.d("success request " + response);
						ResultJsonModel jResult = Parse
								.parseMovieListHot(response);
						if (jResult == null) {
							MyUtil.showDialog(
									"Không thể tải danh sách phim gợi ý",
									IPhimDetailActivity.this);
						} else if (jResult.hasError()) {
							// error register
							String error = jResult.getError();
							MyUtil.showDialog(error, IPhimDetailActivity.this);
						} else {
							mSuggestMovie = (List<MovieModel>) jResult
									.getResult();
							showSuggestMovie();
						}
					}

					@Override
					public void onStart() {
						findViewById(R.id.suggest_loading).setVisibility(
								View.VISIBLE);
					}

					@Override
					public void onFinish() {
						findViewById(R.id.suggest_loading).setVisibility(
								View.GONE);
					}

					@Override
					public void onError(VolleyError error) {
						MyUtil.showDialog("Không thể tải danh sách phim gợi ý "
								+ error.getMessage(), IPhimDetailActivity.this);
					}
				});
	}

	private void showSuggestMovie() {
		if (mSuggestMovie.size() == 0) {
			mSuggestList.setVisibility(View.GONE);
			TextView status = (TextView) findViewById(R.id.status_text);
			status.setVisibility(View.VISIBLE);
			status.setText("Không có danh sách phim gợi ý");
			return;
		}
		mSuggestMovieAdapter = new FilmSuggestAdapter(this, 0, mSuggestMovie);
		mSuggestList.setAdapter(mSuggestMovieAdapter);
	}

	private void resetTab(int idTab) {

		mViewFlipper.setDisplayedChild(idTab);

		// reset
		mDetailTab.setBackgroundColor(mResources.getColor(R.color.dark_gray));
		mDetailTab.setTextColor(mResources.getColor(R.color.gray_text));
		mCommentTab.setBackgroundColor(mResources.getColor(R.color.dark_gray));
		mCommentTab.setTextColor(mResources.getColor(R.color.gray_text));
		mSuggestTab.setBackgroundColor(mResources.getColor(R.color.dark_gray));
		mSuggestTab.setTextColor(mResources.getColor(R.color.gray_text));

		// set select
		switch (idTab) {
		case 0:
			mDetailTab.setBackgroundColor(mResources
					.getColor(R.color.light_gray));
			mDetailTab.setTextColor(mResources.getColor(R.color.white_text));
			break;
		case 1:
			mCommentTab.setBackgroundColor(mResources
					.getColor(R.color.light_gray));
			mCommentTab.setTextColor(mResources.getColor(R.color.white_text));
			break;
		case 2:
			mSuggestTab.setBackgroundColor(mResources
					.getColor(R.color.light_gray));
			mSuggestTab.setTextColor(mResources.getColor(R.color.white_text));
			break;
		}
	}

	private void initModels() {
		mDaoFilm = DaoFactory.getInstance(getApplicationContext())
				.getDaoVideo();
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			mMovie = (MovieModel) bundle.get("movie");
			mHomeId = bundle.getString("home_id");
			if (mMovie == null) {
				MyToast.showToastMessage(this,
						R.string.khong_tim_thay_phim_ban_yeu_cau);
				finish();
				return;
			}
		}

		mResources = getResources();

	}

	private void initViews() {
		
		mEpisode = (TextView) findViewById(R.id.episode_text);
		ImageView thumb = (ImageView) findViewById(R.id.video_thumb);
		UniversalImageUtil.getInstance(this).displayImage(mMovie.getImg(),
				thumb);
		TextView titleVietnamese = (TextView) findViewById(R.id.name_film_vietnamese);
		titleVietnamese.setText(mMovie.getTitle());
		mEpisodeSpinner = (MySpinner) findViewById(R.id.episode_spinner);
		if (mHomeId.equals(AppConstants.ID_IPHIM)) {
			((TextView) findViewById(R.id.episode_text)).setText("Tập 1");
		} else {
			mEpisodeSpinner.setVisibility(View.INVISIBLE);
		}
		findViewById(R.id.play_layout).setOnClickListener(this);

		mViewFlipper = (ViewFlipper) findViewById(R.id.view_flipper);
		mSuggestList = (ListView) findViewById(R.id.suggest_list);
		mSuggestList.setOnItemClickListener(suggestListListener);

		mSuggestList.setOnScrollListener(mScrollingListener); // avoid scrolling
																// lags
		mSuggestList.setSelection(0);

		mCommentView = (CommentView) findViewById(R.id.comment_layout);

		/******************* Tab control **************************/
		mDetailTab = (Button) findViewById(R.id.detail_button);
		mDetailTab.setOnClickListener(this);

		mCommentTab = (Button) findViewById(R.id.comment_button);
		mCommentTab.setOnClickListener(this);

		mSuggestTab = (Button) findViewById(R.id.suggest_button);
		mSuggestTab.setOnClickListener(this);

		setTitle(mMovie.getTitle());

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_iphim_detail);
		initUIBase();
		initModels();
		initViews();
		requestMovieDetail();
	}

	private void requestMovieDetail() {
		final MovieModel movie = mDaoFilm.selectRow(mMovie.getId());
		if (movie != null) {
			Log.d("load movie " + mMovie.getTitle() + " from local");
			mMovie = movie;
			showMovie();
			return;
		}
		VolleyClient.requestDetails(mHomeId, mMovie.getId(),
				new VolleyListener(this) {

					@Override
					public void onSuccess(String response) {
						ResultJsonModel jResult = Parse
								.parseMovieDetail(response);
						if (jResult == null) {
							// error parser
							MyUtil.showDialog("Không thể lấy nội dung phim "
									+ mMovie.getTitle(),
									IPhimDetailActivity.this);
						} else if (jResult.hasError()) {
							// error register
							String error = jResult.getError();
							MyUtil.showDialog(error, IPhimDetailActivity.this);
						} else {
							MovieModel movie = (MovieModel) jResult.getResult();
							mMovie.setDescriptions(movie.getDescriptions());
							mMovie.setTime(movie.getTime());
							mMovie.setTitleEng(movie.getTitleEng());
							mMovie.setType(movie.getType());
							mMovie.setImdb(movie.getImdb());
							mMovie.setFbLink(movie.getFbLink());
							saveMovieToDB();
							Log.d("load movie " + mMovie.getTitle()
									+ " from server");
							showMovie();
						}
					}

					@Override
					public void onStart() {
						Log.d("start request movie detail");
						findViewById(R.id.detail_loading).setVisibility(
								View.VISIBLE);
					}

					@Override
					public void onFinish() {
						Log.d("finish request movie detail");
						findViewById(R.id.detail_loading).setVisibility(
								View.GONE);
					}

					@Override
					public void onError(VolleyError error) {
						MyUtil.showDialog("Không thể lấy nội dung phim "
								+ mMovie.getTitle(), IPhimDetailActivity.this);
					}
				});
	}

	private void saveMovieToDB() {
		mDaoFilm.insertRow(mMovie);
	}

	private void showMovie() {

		TextView titleEnglish = (TextView) findViewById(R.id.name_film_english);
		titleEnglish.setText(mMovie.getTitleEng());

		TextView mTypeView = (TextView) findViewById(R.id.type_text);
		mTypeView.setText(mMovie.getType());

		TextView timeView = (TextView) findViewById(R.id.time_text);
		timeView.setText(mMovie.getTime() + " phút");

		RatingBar imdbRating = (RatingBar) findViewById(R.id.imdb_rating);
		try {
			float rating = Float.valueOf(mMovie.getImdb());
			imdbRating.setRating(rating * 1.0f / 10 * imdbRating.getNumStars());
		} catch (NumberFormatException ne) {
			imdbRating.setVisibility(View.GONE);
		}

		String mime = "text/html";
		String encoding = "utf-8";
		WebView webContent = (WebView) findViewById(R.id.detail_movie);
		webContent.setBackgroundColor(getResources().getColor(
				R.color.black_background));
		webContent.getSettings().setJavaScriptEnabled(true);
		webContent.getSettings().setAppCacheEnabled(true);
		webContent.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		webContent.getSettings().setSupportMultipleWindows(true);
		webContent.getSettings().setSupportZoom(true);
		webContent.getSettings().setBuiltInZoomControls(true);

		// change text color
		String content = mMovie.getDescriptions();
		if (TextUtils.isEmpty(content)) {
			content = "Chưa có mô tả phim";
		}
		content = new StringBuffer("<font color=\"").append(TEXT_COLOR)
				.append("\"").append(" size=\"").append(TEXT_SIZE)
				.append("\">").append(content).append("</font>").toString();
		webContent.loadDataWithBaseURL(null, content, mime, encoding, null);

		// load episodes
		int numEp = mMovie.getEpisodeNum();
		episodes = new String[numEp];
		for (int i = 0; i < numEp; i++) {
			episodes[i] = "Tập " + String.valueOf(i + 1);
		}
		mEpisodeSpinner.initData(this, mMovie.getTitle(), episodes);
		mEpisodeSpinner
				.setItemClickListener(new MySpinner.MySpinerItemClickListener() {

					@Override
					public void onItemClick(int position) {
						if (episodes != null && position < episodes.length) {
							mEpisode.setText(episodes[position]);
							epCurrent = position + 1;
						}
					}
				});
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void setTagMenu() {
		if (mHomeId.equals(AppConstants.ID_IPHIM)) {
			mTagMenu = AppConstants.MENU_IPHIM;
		} else {
			mTagMenu = AppConstants.MENU_ICLIP;
		}
	}

}
